package com.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.beans.*;
import com.manage.util.QiNiuUtil;
import com.manage.util.UserUtils;
import com.beans.*;
import com.beans.page.PageList;
import com.commons.util.Constants;
import com.commons.util.StringUtil;
import com.services.*;
import com.services.impl.PhotoServiceImpl;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author jiangwei
 * @since 18/1/16
 */
@Controller
@RequestMapping("/houseInfo")
public class HouseInfoController extends BaseController {

    @Autowired
    private HouseInfoService houseInfoService;
    @Autowired
    private NeighborhoodService neighborhoodService;
    @Autowired
    private CellInfoService cellInfoService;
    @Autowired
    private PhotoService photoService;
    @Autowired
    private HouseDescService houseDescService;
    @Autowired
    private HouseFavoriteService houseFavoriteService;

    /***
     * 查询列表(全部)
     *
     * @param houseInfo
     * @param request
     * @return
     */
    @RequiresPermissions("houseInfo:view")
    @RequestMapping(value = {"", "/", "list"})
    public String list(HouseInfo houseInfo, HttpServletRequest request) {
        List<Neighborhood> neighborhoodList = neighborhoodService.queryList(new Neighborhood());

        request.setAttribute("houseInfo", houseInfo);
        request.setAttribute("neighborhoodList", neighborhoodList);

        return "houseInfo/list";
    }

    /**
     * 异步获取list资源(全部)
     *
     * @param pageList
     * @param houseInfo
     * @return
     */
    @RequiresPermissions("houseInfo:view")
    @RequestMapping("asynList")
    @ResponseBody
    public PageList asynList(PageList pageList, HouseInfo houseInfo) {
        houseInfo.setUpdateBy(UserUtils.getUser().getUserId());
        return houseInfoService.queryPageByHouseInfo(pageList, houseInfo);
    }

    /**
     * 新增修改
     *
     * @param houseInfo
     * @return
     */
    @RequiresPermissions("houseInfo:edit")
    @RequestMapping(value = {"add", "edit"}, method = RequestMethod.POST)
    public String edit(HouseInfo houseInfo, Model model, String type) {
        List labelList = new ArrayList();//标签
        List<Photo> photoList = new ArrayList<Photo>();//房源图
        List<Photo> photoHXList = new ArrayList<Photo>();//户型图
        List<HouseDesc> houseDescList = new ArrayList<HouseDesc>();//房源描述

        if (houseInfo.getHouseId() != null) {
            houseInfo = houseInfoService.queryById(houseInfo.getHouseId());

            if(!StringUtil.isEmpty(houseInfo.getLabel())){
                labelList = Arrays.asList(houseInfo.getLabel().replace("|", ",").split(","));
            }

            Photo photo = new Photo();
            photo.setRelationId(houseInfo.getHouseId());
            photo.setRelationType(Constants.oneLong);
            photo.setCategory(Constants.minus);
            photoList = photoService.queryList(photo);

            //房源户型照片
            photo.setCategory(Constants.one);
            photoHXList = photoService.queryList(photo);

            HouseDesc houseDesc = new HouseDesc();
            houseDesc.setRelationId(houseInfo.getHouseId());
            houseDescList = houseDescService.queryList(houseDesc);

            type = String.valueOf(houseInfo.getHouseType());
        }

        List<Neighborhood> neighborhoodList = neighborhoodService.queryList(new Neighborhood());

        model.addAttribute("storeUrl", UserUtils.storeUrl);

        model.addAttribute("houseInfo", houseInfo);

        model.addAttribute("labelList", labelList);
        model.addAttribute("neighborhoodList", neighborhoodList);

        model.addAttribute("photoList", photoList);
        model.addAttribute("photoHXList", photoHXList);

        if (houseDescList.size() > 0) {
            for (int i = 0; i < houseDescList.size(); i++) {
                model.addAttribute("houseDesc" + i, houseDescList.get(i));
            }
        }

        String returnVaLue = "houseInfo/edit";//默认进二手别墅编辑或添加页面
        if (!StringUtil.isEmpty(type) && type.equals("2")) {
            returnVaLue = "houseInfo/editHz";//进二手豪宅编辑或添加页面
        }
        return returnVaLue;
    }

    @RequiresPermissions("houseInfo:edit")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public String save(HouseInfo houseInfo, HttpServletRequest request,
                       @RequestParam(value = "imgFileIds", required = false) String[] imgFileIds,
                       @RequestParam(value = "imgFileDes", required = false) String[] imgFileDes,
                       @RequestParam(value = "imgFileHXIds", required = false) String[] imgFileHXIds,
                       @RequestParam(value = "imgFileHXDes", required = false) String[] imgFileHXDes,
                       @RequestParam(value = "categoryHX", required = false) String categoryHX,
                       @RequestParam(value = "categoryYY", required = false) String categoryYY,
                       @RequestParam(value = "categoryJG", required = false) String categoryJG,
                       @RequestParam(value = "categoryWZ", required = false) String categoryWZ,
                       @RequestParam(value = "hxId", required = false) Long hxId,
                       @RequestParam(value = "yyId", required = false) Long yyId,
                       @RequestParam(value = "jgId", required = false) Long jgId,
                       @RequestParam(value = "wzId", required = false) Long wzId) {
        int result = -1;

        if(!StringUtil.isEmpty(houseInfo.getLabel())){
            houseInfo.setLabel(houseInfo.getLabel().replace(",", "|"));
        }

        if (houseInfo.getTotalArea() == null) {
            houseInfo.setTotalArea(houseInfo.getFactArea());//不为空
        }

        if (houseInfo.getHouseId() == null) {
            houseInfo.setCreateBy(UserUtils.getUser().getUserId());
            houseInfo.setUpdateBy(UserUtils.getUser().getUserId());
            result = houseInfoService.add(houseInfo);
            if (result > 0) {
                houseInfo.setHouseNo(String.valueOf(houseInfo.getHouseId()));
                result = houseInfoService.update(houseInfo);
            }
        } else {
            houseInfo.setUpdateBy(UserUtils.getUser().getUserId());
            result = houseInfoService.update(houseInfo);
        }

        if (result > 0) {
            Photo photo = new Photo();
            //
            photo.setCreateBy(UserUtils.getUser().getUserId());
            photo.setUpdateBy(UserUtils.getUser().getUserId());
            photo.setRelationType(Constants.oneLong);//房源类型

            //删除和更新图片
            PhotoServiceImpl psi = new PhotoServiceImpl();
            psi.photo(photoService, houseInfo.getHouseId(), photo, imgFileIds, imgFileDes, imgFileHXIds, imgFileHXDes);
            QiNiuUtil.handleQUrl(imgFileIds, imgFileHXIds);

            HouseDesc houseDesc = new HouseDesc();
            houseDesc.setCreateBy(UserUtils.getUser().getUserId());
            houseDesc.setUpdateBy(UserUtils.getUser().getUserId());
            houseDesc.setRelationId(houseInfo.getHouseId());
            houseDesc.setRelationType(Constants.oneLong);//房源类型

            //保存房源描述(核销卖点)
            if (!StringUtil.isEmpty(categoryHX)) {
                saveHouseDes(houseDesc, Constants.one, categoryHX, hxId);
            }
            //保存房源描述(出售原因)
            if (!StringUtil.isEmpty(categoryYY)) {
                saveHouseDes(houseDesc, Constants.two, categoryYY, yyId);
            }
            //保存房源描述(景观特点)
            if (!StringUtil.isEmpty(categoryJG)) {
                saveHouseDes(houseDesc, Constants.three, categoryJG, jgId);
            }
            //保存房源描述(坐落位置)
            if (!StringUtil.isEmpty(categoryWZ)) {
                saveHouseDes(houseDesc, Constants.four, categoryWZ, wzId);
            }
        }

        return "redirect:list";
    }

    @RequiresPermissions("houseInfo:delete")
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(Long houseId) {
        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setHouseId(houseId);
        houseInfo.setUpdateBy(UserUtils.getUser().getUserId());
        int result = houseInfoService.delete(houseInfo);

        if (result > 0) {
            //删除关联图片
            Photo photo = new Photo();
            photo.setUpdateBy(UserUtils.getUser().getUserId());
            photo.setRelationType(Constants.oneLong);//房源类型
            photo.setRelationId(houseId);

            photoService.delete(photo);
            //删除关联描述
            HouseDesc houseDesc = new HouseDesc();
            houseDesc.setUpdateBy(UserUtils.getUser().getUserId());
            houseDesc.setRelationId(houseId);

            houseDescService.delete(houseDesc);
        }
        //TODO  成功失败结果页面
        return result;
    }

    /**
     * 房源描述
     */
    @RequestMapping("queryCellInfo")
    @ResponseBody
    public JSONObject queryCellInfo(Long nbhId, String cellInfoId, Integer unitNoId) {
        CellInfo cellInfo = new CellInfo();
        cellInfo.setNbhId(nbhId);
        cellInfo.setBuildingNo(cellInfoId);
        if(StringUtil.isEmpty(unitNoId)){
            unitNoId=0;
        }
        cellInfo.setUnitNum(unitNoId);
        List<CellInfo> cellInfos = cellInfoService.queryList(cellInfo);

        if(cellInfoId==null && unitNoId == 0){
            for  ( int  i  =   0 ; i  <  cellInfos.size()  -   1 ; i ++ )  {
                for  ( int  j  =  cellInfos.size()  -   1 ; j  >  i; j -- )  {
                    if  (cellInfos.get(j).getBuildingNo().equals(cellInfos.get(i).getBuildingNo()))  {
                        cellInfos.remove(j);
                    }
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", cellInfos);
        return jsonObject;
    }

    /***
     * 收藏
     *
     * @param houseId
     */
    @RequiresPermissions("houseInfo:collection")
    @RequestMapping("collection")
    @ResponseBody
    public Object collection(Long houseId) {
        int result = 0;
        HouseFavorite houseFavorite = new HouseFavorite();

        houseFavorite.setHouseId(houseId);
        houseFavorite.setCreateBy(UserUtils.getUser().getUserId());
        houseFavorite.setUpdateBy(UserUtils.getUser().getUserId());
        houseFavorite.setStaus(Constants.zero);

        List houseFavorites = houseFavoriteService.queryListByCollection(houseFavorite);

        if (houseFavorites.size() > 0) {
            houseFavorite.setStaus(0);
            result = houseFavoriteService.update(houseFavorite);
        } else {
            result = houseFavoriteService.add(houseFavorite);
        }

        //TODO  成功失败结果页面
        return result;
    }

    /***
     * 取消收藏
     *
     * @param houseId
     */
    @RequiresPermissions("houseInfo:uncollection")
    @RequestMapping("uncollection")
    @ResponseBody
    public Object uncollection(Long houseId) {
        int result = 0;
        HouseFavorite houseFavorite = new HouseFavorite();

        houseFavorite.setHouseId(houseId);
        houseFavorite.setCreateBy(UserUtils.getUser().getUserId());
        houseFavorite.setUpdateBy(UserUtils.getUser().getUserId());
        houseFavorite.setStaus(Constants.one);
        houseFavorite.setStaus(1);

        result = houseFavoriteService.update(houseFavorite);

        //TODO  成功失败结果页面
        return result;
    }

    //保存房源描述
    private void saveHouseDes(HouseDesc houseDesc, Integer category, String categoryHX, Long hxId) {
        houseDesc.setCategory(category);
        houseDesc.setText(categoryHX);

        if (StringUtil.isEmpty(hxId)) {
            houseDescService.add(houseDesc);
        } else {
            houseDesc.setHouseDescId(hxId);

            houseDescService.update(houseDesc);
        }
    }

    /**
     * 房源详情
     *
     * @param houseInfo
     * @return
     */
    @RequiresPermissions("houseInfo:detail")
    @RequestMapping("detail")
    public String detail(HouseInfo houseInfo, Model model) {
        String type = "1";
        List labelList = new ArrayList();//标签
        List<Photo> photoList = new ArrayList<Photo>();//房源图
        List<Photo> photoHXList = new ArrayList<Photo>();//户型图
        List<HouseDesc> houseDescList = new ArrayList<HouseDesc>();//房源描述

        if (!StringUtil.isEmpty(houseInfo.getHouseId())) {
            houseInfo = houseInfoService.queryById(houseInfo.getHouseId());

            labelList = Arrays.asList(houseInfo.getLabel().replace("|", ",").split(","));

            Photo photo = new Photo();
            photo.setRelationId(houseInfo.getHouseId());
            photo.setRelationType(Constants.oneLong);
            photo.setCategory(Constants.minus);
            photoList = photoService.queryList(photo);

            //房源户型照片
            photo.setCategory(Constants.one);
            photoHXList = photoService.queryList(photo);

            HouseDesc houseDesc = new HouseDesc();
            houseDesc.setRelationId(houseInfo.getHouseId());
            houseDescList = houseDescService.queryList(houseDesc);

            type = String.valueOf(houseInfo.getHouseType());
        }

        List<Neighborhood> neighborhoodList = neighborhoodService.queryList(new Neighborhood());

        model.addAttribute("houseInfo", houseInfo);

        model.addAttribute("labelList", labelList);
        model.addAttribute("neighborhoodList", neighborhoodList);

        model.addAttribute("photoList", photoList);
        model.addAttribute("photoHXList", photoHXList);

        model.addAttribute("storeUrl", UserUtils.storeUrl);

        if (houseDescList.size() > 0) {
            for (int i = 0; i < houseDescList.size(); i++) {
                model.addAttribute("houseDesc" + i, houseDescList.get(i));
            }
        }

        String returnVaLue = "houseInfo/detail";//默认进二手别墅编辑或添加页面
        if (!StringUtil.isEmpty(type) && type.equals("2")) {
            returnVaLue = "houseInfo/detailHz";//进二手豪宅编辑或添加页面
        }
        return returnVaLue;
    }

    /***
     * 聚焦
     * @param houseId
     * @return
     */
    @RequiresPermissions("houseInfo:focus")
    @RequestMapping("focusing")
    @ResponseBody
    public Object focusing(Long houseId) {
        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setHouseId(houseId);
        houseInfo.setUpdateBy(UserUtils.getUser().getUserId());
        houseInfo.setFocusFlag("1");

        int result = houseInfoService.update(houseInfo);

        //TODO  成功失败结果页面
        return result;
    }

    /***
     * 取消聚焦
     * @param houseId
     * @return
     */
    @RequiresPermissions("houseInfo:focus")
    @RequestMapping("unfocusing")
    @ResponseBody
    public Object unfocusing(Long houseId) {
        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setHouseId(houseId);
        houseInfo.setUpdateBy(UserUtils.getUser().getUserId());
        houseInfo.setFocusFlag("0");

        int result = houseInfoService.update(houseInfo);

        //TODO  成功失败结果页面
        return result;
    }

    /**
     * 不存在  返回true 存在返回false,条件为空返回false
     *
     * @param houseInfo
     * @param request
     * @return
     */
    @RequestMapping("notExists")
    @ResponseBody
    public Object exists(HouseInfo houseInfo, HttpServletRequest request) {

        List<HouseInfo> houseInfos = houseInfoService.queryExists(houseInfo);

        if (StringUtil.isEmpty(houseInfo.getHouseId())) {
            return !(houseInfos.size() > 0);
        } else if (houseInfos.size() > 0) {
            HouseInfo hi = houseInfoService.queryById(houseInfo.getHouseId());
            if (hi.getRoomNo().equals(houseInfo.getRoomNo())) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
}
